import { db, models } from '../../db';
import { getUserInfo, getUserRole } from './user';
import { Battle } from '../battle';
import type { BattleReward, UserInfo, UserRole, BattleResult } from '../types';

const { config_hero: ConfigHeroModel, user_item: UserItemModel } = models;

export const bossBattle = async (user_id: string, data: Record<string, any>) => {
  const transaction = await db.transaction();

  return new Promise(async (resolve, reject) => {
    try {
      const bossLing = await UserItemModel.findOne({ where: { user_id, item_id: 1013 } });

      if (!bossLing) {
        return;
      }

      if (bossLing.dataValues.count <= 0) {
        reject('挑战令数量不足');
      }

      // 获取我方阵容
      const { id, level } = data;

      const { name: ownName } = (await getUserInfo(user_id)) as UserInfo;
      const userRole: UserRole[] = await getUserRole(user_id);
      const own = userRole.filter(v => v.position[0] > 0 && v.position[0] < 4);

      // 获取敌方阵容
      const boos = await ConfigHeroModel.findOne({ where: { id } });

      if (!boos) {
        return;
      }

      const { id: bossId, name, avatar, skill1, skill2, skill3 } = boos.dataValues;

      const foe: UserRole[] = [
        {
          id: 'boss',
          heroId: bossId,
          heroName: name,
          heroAvatar: avatar,
          level: 1,
          exp: 0,
          position: [2, 1],
          equip: [],
          talent: [],
          hp: 9999999999,
          attack: 50000 * level,
          // attack: 150000 * level,
          defence: 0,
          speed: 0,
          skill1: skill1 + 3,
          skill2: skill2 + 3,
          skill3: skill3,
        },
      ];

      const res = await Battle(own, foe, 1, ownName, 'Boss');

      const { reward } = res;

      await UserItemModel.update(
        { count: bossLing.dataValues.count - 1 },
        { where: { id: bossLing.dataValues.id }, transaction },
      );

      if (reward.length > 0) {
        const gongxunLing = await UserItemModel.findOne({
          where: { user_id, item_id: reward[0].id },
        });

        const { id, count } = reward[0];

        if (!gongxunLing) {
          await UserItemModel.create(
            {
              user_id,
              item_id: id,
              count: count,
            },
            { transaction },
          );
        } else {
          await UserItemModel.update(
            { count: gongxunLing.dataValues.count + count },
            { where: { user_id, item_id: id }, transaction },
          );
        }
      }

      await transaction.commit();
      resolve(res);
    } catch (error) {
      console.log(error);
      await transaction.rollback();
    }
  });
};
